#!/usr/bin/env python3
"""
新能源汽车舆情分析系统启动脚本
"""

import os
import sys
import subprocess
import time
import signal
from multiprocessing import Process

def check_dependencies():
    """检查依赖是否安装"""
    try:
        import fastapi
        import pymongo
        import requests
        from bs4 import BeautifulSoup
        print("✅ 所有依赖已安装")
        return True
    except ImportError as e:
        print(f"❌ 缺少依赖: {e}")
        print("请运行: pip install -r requirements.txt")
        return False

def check_environment():
    """检查环境变量"""
    api_key = os.getenv('DASHSCOPE_API_KEY')
    if not api_key:
        print("❌ 未设置DASHSCOPE_API_KEY环境变量")
        print("请设置你的阿里云百练API密钥")
        return False
    
    print("✅ 环境变量配置正确")
    return True

def start_web_server():
    """启动Web服务器"""
    print("🚀 启动Web服务器...")
    subprocess.run([sys.executable, "main.py"])

def start_scheduler():
    """启动任务调度器"""
    print("⏰ 启动任务调度器...")
    subprocess.run([sys.executable, "scheduler.py"])

def main():
    """主函数"""
    print("=" * 50)
    print("🚗 新能源汽车舆情分析系统")
    print("=" * 50)
    
    # 检查依赖
    if not check_dependencies():
        sys.exit(1)
    
    # 检查环境变量
    if not check_environment():
        sys.exit(1)
    
    # 创建必要的目录
    os.makedirs("static", exist_ok=True)
    os.makedirs("templates", exist_ok=True)
    os.makedirs("reports", exist_ok=True)
    
    print("\n选择运行模式:")
    print("1. 启动Web服务器 (默认)")
    print("2. 启动任务调度器")
    print("3. 同时启动Web服务器和调度器")
    print("4. 执行一次性任务")
    print("5. 退出")
    
    choice = input("\n请选择 (1-5): ").strip() or "1"
    
    if choice == "1":
        start_web_server()
    elif choice == "2":
        start_scheduler()
    elif choice == "3":
        print("🔄 同时启动Web服务器和调度器...")
        
        # 启动Web服务器进程
        web_process = Process(target=start_web_server)
        web_process.start()
        
        # 启动调度器进程
        scheduler_process = Process(target=start_scheduler)
        scheduler_process.start()
        
        try:
            # 等待进程
            web_process.join()
            scheduler_process.join()
        except KeyboardInterrupt:
            print("\n🛑 正在停止服务...")
            web_process.terminate()
            scheduler_process.terminate()
            web_process.join()
            scheduler_process.join()
            
    elif choice == "4":
        print("🔄 执行一次性任务...")
        subprocess.run([sys.executable, "scheduler.py", "--once"])
    elif choice == "5":
        print("👋 再见!")
        sys.exit(0)
    else:
        print("❌ 无效选择")
        sys.exit(1)

if __name__ == "__main__":
    main()
